<?php
class ViewstateAction extends ZMAction
{
    //获取状态信息
    public function getAll(){
        $Model = M('Viewstate');
        $userid = $_SESSION['user']['userid'];
        $result = $Model->where("uid=$userid")->select();
        $ret = array();
        foreach($result as $row){
            $ret[$row['name']] = $row['value'];
        }
        $this->ajaxReturn($ret,count($ret));
    }
    
    public function setValue(){
        $name = $_REQUEST['name'];
        $value = $_REQUEST['value'];
        $userid = $_SESSION['user']['userid'];
        
        $map['uid'] = $userid;
        $map['name'] = $name;
        $Model = M('Viewstate');
        $result = $Model->where($map)->find();
        if($result){
            $id = $result['id'];
            $data['value'] = $value;
            $Model->where("id=$id")->save($data);
        }else{
            $map['value'] = $value;
            $Model->add($map);
        }
        $this->success('ok');
    }
    
    public function clear(){
        $name = $_REQUEST['name'];
        $userid = $_SESSION['user']['userid'];
        $map['uid'] = $userid;
        $map['name'] = $name;
        $Model = M('Viewstate');
        $Model->where($map)->delete();
        $this->success('ok');
    }
    
    public function read(){
        $Model = M('Viewstate');
        $userid = $_SESSION['user']['userid'];
        $result = $Model->where("uid=$userid")->select();
        $this->ajaxRetArray($result);
    }
    
    public function save(){
        $data = $_REQUEST['data'];
        $data = str_replace("\\\"","\"",$data);
        $data = str_replace("\\\\","\\",$data);
        $datas = json_decode($data);
        $userid = $_SESSION['user']['userid'];
        $Model = M('Viewstate');
        $where['uid'] = $userid;
        unset($data);
        foreach($datas as &$item){
            $data['uid'] = $userid;
            $data['name'] = $item->name;
            $data['value'] = $item->value;
            $where['name'] = $item->name;
            $res = $Model->where($where)->find();
            if($res){
                $Model->where($where)->save($data);
            }else{
                $Model->add($data);
            }
        }
        $this->success('ok');
    }
}
?>